package com.quarkus.system;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @Author: TongRui乀
 * @Date: 2021/6/5 16:25
 * @description：
 */
public class TestShutDownHook {

        public static void main(String[] args) {
            ExecutorService executorService = Executors.newFixedThreadPool(5);
            for (int i = 0; i < 5 ; i++) {
                Thread task = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getName() + " start");
                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + " end");
                    }
                });
                executorService.submit(task);
            }

            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                System.out.println("shutdown hook");
                executorService.shutdown();
                try {
                    boolean b = executorService.awaitTermination(20, TimeUnit.SECONDS);
                    if (b) {
                        executorService.shutdownNow();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }));

            System.out.println("main start");
            try {
                Thread.sleep(5000);
                System.exit(0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("main end");
        }

}
